package com.wanqing.community.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;

/**
 * 文件处理的工具类
 */
public class FileTools {
	
	//private static Logger log = Logger.getLogger(FileTools.class);

	/**
	 * <p>文件重命名<p>
	 * <p>modifiContent:<p>
	 * @param sourceFileName
	 * @return
	 */
	public static String fileReName(String sourceFileName){
		String distFileName = "";
		if(!StringTools.isEmptyOrNull(sourceFileName)){
			String ext = fileExetName(sourceFileName);
			distFileName = UUID.uuId()+"."+ext;
		}
		return distFileName;
	}
	
	public static String renameTo(String sourceFileName) {
		String distFileName = "";
		if(!StringTools.isEmptyOrNull(sourceFileName)){
			String ext = fileExetName(sourceFileName);
			//distFileName = new Date().getTime()+"."+ext;
			distFileName = System.nanoTime()+"."+ext;
		}
		return distFileName;
	}
	
	/**
	 * <p>Description:根据文件得到文件名称和扩展名<p>
	 * <p>modifiContent:<p>
	 * @param sourceFileName
	 * @return
	 */
	public static String[] fileName(String sourceFileName){
		String[] result = new String[2];
		if(StringTools.isEmptyOrNull(sourceFileName)){
			return null;
		}
		int index = sourceFileName.lastIndexOf(".");
		String filename = sourceFileName.substring(0, index);
		String ext = sourceFileName.substring(index+1);
		result[0] = filename;
		result[1] = ext;
		return result;
	}
	
	/**
	 * <p>文件重命名<p>
	 * <p>modifiContent:<p>
	 * @param sourcSeFileName 原文件
	 * @param ext 重命名后的扩展名
	 * @return
	 */
	public static String fileReName(String sourcSeFileName,String ext){
		String distFileName = "";
		if(!StringTools.isEmptyOrNull(sourcSeFileName)){
			distFileName = UUID.uuId()+"."+ext;
		}
		return distFileName;
	}
	
	/**
	 * <p>将content字符串写入到文件file中<p>
	 * <p>modifiContent:<p>
	 * @param file
	 * @param content
	 */
	public static void writeFile(File file,String content){
		FileWriter fw = null;
		BufferedWriter bw = null;
		try{
			fw = new FileWriter(file);
			int size = content.length();
			bw = new BufferedWriter(fw,size);
			bw.write(content);
			bw.flush();			
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(null!=bw){
					bw.close();
				}
				if(null!=fw){
					fw.close();
				}
			} catch (IOException e) {				
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * <p>读取文件file中的内容<p>
	 * <p>modifiContent:<p>
	 * @param file
	 */
	public static String readerFile(File file){
		StringBuilder sb = new StringBuilder();
		FileReader fr = null;
		BufferedReader br = null;
		try{
			fr = new FileReader(file);
			br = new BufferedReader(fr,4096);
			String line = null;
			while((line=br.readLine())!=null){
				sb.append(line);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(null!=br){
					br.close();
				}
				if(null!=fr){
					fr.close();
				}
			} catch (IOException e) {				
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	/**
	 * <p>得到文件的扩展名<p>
	 * <p>modifiContent:<p>
	 * @param sourceFileName
	 * @return
	 */
	public static String fileExetName(String sourceFileName){
		String ext = "";
		if(!StringTools.isEmptyOrNull(sourceFileName)){
			int index = sourceFileName.lastIndexOf(".");
			ext = sourceFileName.substring(index+1);
		}
		return ext;
	}
	
	/**
	 * <p>检查文件类型<p>
	 * <p>modifiContent:<p>
	 * @param filesorts 文件类型字符串数组，到KeyConstant中查找
	 * @param ext 要检查的文件类型
	 * @return boolean
	 */
	public static boolean checkFileSort(String[] filesorts,String ext){
		boolean flag = false;
		if(null!=filesorts){
			Map<String, String> map = new HashMap<String, String>();
			for (int i = 0; i < filesorts.length; i++) {
				map.put(filesorts[i], null);
			}
			flag = map.containsKey(ext);
		}
		return flag;		
	}
	
	/**
	 * <p>删除文件<p>
	 * <p>modifiContent:<p>
	 * @param dir 路径
	 * @param filename 文件名
	 */
	public static void deleteFile(String dir,String filename){
		if(!StringTools.isEmptyOrNull(dir) && !StringTools.isEmptyOrNull(filename)){			
			File file = new File(dir+filename);
			if(file.exists()){				
				file.delete();
			}
		}
	}
	
	/**
	 * <p>删除文件<p>
	 * <p>modifiContent:<p>
	 * @param dir 路径
	 * @param filenames 文件名数组
	 */
	public static void deleteFile(String dir,String[] filenames){
		if(!StringTools.isEmptyOrNull(dir) && null!=filenames && filenames.length>0){
			File file = null;
			for (String filename : filenames) {				
				file = new File(dir+filename);				
				deleteFile(file);
			}
		}
	}
	
	/**
	 * <p>删除文件<p>
	 * <p>modifiContent:<p>
	 * @param filepath 要删除文件的全路径地址
	 */
	public static void deleteFile(String filepath){
		if(!StringTools.isEmptyOrNull(filepath)){
			File file = new File(filepath);
			if(file.exists()){
				file.delete();
			}
		}
	}
	
	/**
	 * <p>删除文件<p>
	 * <p>modifiContent:<p>
	 * @param filepaths 要删除文件的全路径地址数组
	 */
	public static void deleteFile(String[] filepaths){
		if(null!=filepaths && filepaths.length>0){
			File file = null;
			for (String filepath : filepaths) {
				if(StringTools.isNotEmptyOrNull(filepath)){					
					file = new File(filepath);					
					deleteFile(file);
				}								
			}
		}
	}
	
	/**
	 * <p>删除文件<p>
	 * <p>modifiContent:<p>
	 * @param file 要删除文件
	 */
	public static void deleteFile(File file){
		if(null!=file && file.exists() && file.isFile()){			
			file.delete();			
		}
	}
	
	/**
	 * <p>删除文件<p>
	 * <p>modifiContent:<p>
	 * @param files 要删除文件数组
	 */
	public static void deleteFile(File[] files){
		if(null!=files && files.length>0){
			for (File file : files) {
				deleteFile(file);
			}
		}
	}
	
	/**
	 * <p>判断文件是否存在，存在返回true，否则返回false<p>
	 * <p>modifiContent:<p>
	 * @param filepath 文件所在的全路径
	 * @return boolean
	 */
	public static boolean fileExists(String filepath){
		File file = new File(filepath);
		return file.exists();
	}
	
	/**
	 * <p>Description:下载文件<p>
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @param dir 文件所在目录
	 * @param storeName 文件在目录下的名称
	 * @param contentType 
	 * @param realName 文件真实名
	 */
	public static void download(HttpServletRequest request,HttpServletResponse response,String dir,String storeName,String contentType,String realName){
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		String ctxPath = request.getSession().getServletContext().getRealPath("/")+dir+File.separator;
		String downloadPath = ctxPath+storeName;		
		File file =  new File(downloadPath);
		long fileLength = file.length();			
		try {			
			String fileNameTemp = new String(realName.getBytes("GBK"),
			"ISO8859-1");			
			bis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[bis.available()];
            bis.read(buffer);            
            //清空response
			response.reset();
			response.setContentType(contentType);
			response.addHeader("Content-Disposition", "attachment; filename=\""
					+ fileNameTemp + "\"");
			response.addHeader("Content-Length", "" + fileLength);
            bos = new BufferedOutputStream(response.getOutputStream());
            bos.write(buffer);
            bos.flush();           
		} catch (FileNotFoundException e) {			
			e.printStackTrace();
		} catch (IOException e) {			
			e.printStackTrace();
		}finally{
			try {
				if(null!=bis){
					bis.close();
				}
				if(null!=bos){
					bos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * <p>Description:下载文件<p>
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @param dir 文件在目录下的名称
	 * @param contentType
	 * @param realName 文件真实名
	 */
	public static void download(HttpServletRequest request,HttpServletResponse response,String dir,String contentType,String realName){
		download(request, response, dir, realName, contentType, realName);
	}
	
	/**
	 * <p>Description:下载文件<p>
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @param dir 文件在目录下的名称
	 * @param contentType
	 * @param realName 文件真实名
	 */
	public static void download(HttpServletRequest request,HttpServletResponse response,String dir,String realName){
		download(request, response, dir, "application/octet-stream", realName);
	}
	
	/**
	 * <p>Description:使用Spring MVC上传文件<p>
	 * <p>modifiContent:<p>
	 * @param is 输入流
	 * @param uploadPath 上传到服务器的地址
	 * @param fileName 文件名
	 * @throws IOException 
	 */
	public static void springMVCUploadFile(InputStream is,String uploadPath,String fileName) throws IOException{
		FileUtils.copyInputStreamToFile(is, new File(uploadPath,fileName));
	}
}
